import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, logout as apiLogout } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('admin_token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('admin_user') || '{}'))

  const isLoggedIn = computed(() => !!token.value)

  const login = async (credentials) => {
    try {
      console.log('发送登录请求到:', '/admin/login', credentials)
      const response = await apiLogin(credentials) // 修改：使用 apiLogin 而不是 request.post
      console.log('登录响应:', response)
      
      if (response.code === 200 && response.data) {
        token.value = response.data.token
        userInfo.value = response.data.user // 修改：使用 userInfo 而不是 user
        
        // 存储到 localStorage
        localStorage.setItem('admin_token', response.data.token)
        localStorage.setItem('admin_user', JSON.stringify(response.data.user))
        
        return response.data
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('登录请求失败:', error)
      if (error.response) {
        throw new Error(error.response.data?.message || '服务器错误')
      } else if (error.request) {
        throw new Error('网络连接失败，请检查网络')
      } else {
        throw new Error(error.message || '登录失败')
      }
    }
  }

  const logout = async () => {
    try {
      await apiLogout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      token.value = ''
      userInfo.value = {}
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout
  }
})